﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace ClearDir
{

//    cmd延时执行
//choice /t 2 /d y /n >nul   
//echo del>%~dp0test.txt
//pause del %~dp0test.txt

    public class ClearTool
    {
        /// <summary>
        /// 清空多个文件目录或文件
        /// </summary>
        public static void ClearDelet(string[] paths)
        {
            foreach (string path in paths) ClearDelet(path);
        }

        /// <summary>
        /// 清空目录或文件
        /// </summary>
        public static void ClearDelet(string path)
        {
            if (File.Exists(path))
            {
                if (path.Equals(DependentFiles.curExecutablePath())) Program.autoDelet = true;
                else  ClearDeletFile(path);
            }
            if (Directory.Exists(path)) ClearDeletDirectory(path);
        }


        /// <summary>
        /// 先清空目录中的所有文件和子目录内容，再删除当前目录
        /// </summary>
        public static void ClearDeletDirectory(string dir)
        {
            if (Directory.Exists(dir))
            {
                try
                {
                    // 清除目录下的所有文件
                    foreach (String iteam in Directory.GetFiles(dir))
                    {
                        ClearDeletFile(iteam);
                    }

                    // 清除目录下的所有子目录
                    foreach (String iteam in Directory.GetDirectories(dir))
                    {
                        ClearDeletDirectory(iteam);
                    }

                    String newName = System.IO.Directory.GetParent(dir).FullName + "\\$";
                    while (File.Exists(newName)) newName += "$";

                    // 清除当前目录
                    Directory.Move(dir, newName);   // 重命名当前目录，清除目录名信息
                    Directory.Delete(newName);      // 清除当前目录
                }
                catch (Exception ex) { }
            }
        }

        /// <summary>
        /// 先清空文件内容，再删除
        /// </summary>
        public static void ClearDeletFile(string file)
        {
            if (File.Exists(file))
            {
                try
                {
                    if (file.ToLower().EndsWith(".exe") )
                    {
                        // 结束进程
                        ProcessTool.killProcessExe(file);

                        // 等待进程结束，等30秒
                        long preTime = DateTime.Now.AddSeconds(30).Ticks;
                        while (ProcessTool.ProcessIsRunning(file) && DateTime.Now.Ticks < preTime) ;

                        // 进程结束后等3秒
                        preTime = DateTime.Now.AddSeconds(3).Ticks;
                        while (DateTime.Now.Ticks < preTime) ;
                    }

                    ClearFile(file);            // 清空文件内容

                    String newName = System.IO.Directory.GetParent(file).FullName + "\\$";
                    while (File.Exists(newName)) newName += "$";

                    File.Move(file, newName);   // 重命名文件，清除文件名称信息
                    File.Delete(newName);       // 删除文件
                }
                catch (Exception ex) { }
            }
        }

        /// <summary>
        /// 清空文件内容
        /// </summary>
        public static void ClearFile(string file)
        {
            if (File.Exists(file))
            {
                try
                {
                    int SIZE = 1024 * 10240;
                    byte[] array = new byte[SIZE];
                    array.Initialize();

                    FileStream s = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, SIZE, FileOptions.RandomAccess);

                    // 清空原有文件内容
                    while (s.Position + SIZE <= s.Length - 1)
                    {
                        s.Write(array, 0, SIZE);
                    }
                    int reminds = (int)(s.Length - s.Position);
                    if (reminds > 0) s.Write(array, 0, reminds);

                    // 清除文件长度信息
                    s.SetLength(0);
                    s.Close();
                }
                catch (Exception ex) { }
            }
        }

    }


    public class ProcessTool
    {
        public static void test()
        {
            String processName = "ChargeModule_V4";
            killProcess(processName);
        }

        /// <summary>
        /// 结束指定Exe对应的进程
        /// </summary>
        public static void killProcessExe(String exeFile)
        {
            if (File.Exists(exeFile))
            {
                String name = Path.GetFileNameWithoutExtension(exeFile);
                killProcess(name);
            }
        }

        /// <summary>
        /// 结束指定名称的进程
        /// </summary>
        public static void killProcess(String processName)
        {
            //Process current = Process.GetCurrentProcess();    // 当前进程
            //current.ProcessName                               // 当前进程名

            Process[] processes = Process.GetProcessesByName(processName); // 获取指定名称的进程
            foreach (Process process in processes)
            {
                try
                {
                    process.Kill();
                }
                catch (Exception ex) { }
            }
        }

        /// <summary>
        /// 判断指定名称的进程是否正在运行
        /// </summary>
        public static bool ProcessIsRunning(String processName)
        {
            if (File.Exists(processName)) processName = Path.GetFileNameWithoutExtension(processName);

            Process[] processes = Process.GetProcessesByName(processName); // 获取指定名称的进程
            return (processes != null && processes.Length > 0);
        }
    }

}
